package main

import (
	"fmt"
	"goInAction/retriever/iretriever"
	"goInAction/retriever/mock"
	real2 "goInAction/retriever/real"
)

const url = "http://www.baidu.com"

func main() {
	var retriever iretriever.Retriever = getRetriever("baidu")
	get := retriever.Get(url)
	fmt.Println(get)

	//可以看到接口中包含两个部分,一部分是接口的实际类型,还有就是实际类型的值
	fmt.Printf("%T %v \n", retriever, retriever)

	var retriever2 iretriever.Retriever = getRetriever("mock")
	fmt.Println(retriever2.Get("aaaa"))

	fmt.Printf("%T %v \n", retriever2, retriever2)

	inspect(retriever)

	//type assertion; 相当于类型装换
	realRetriever, ok := retriever.(real2.RetrieverForBaidu)
	if ok {
		fmt.Println("Type Assertion...", realRetriever.Name, realRetriever.Title)
	} else {
		fmt.Println("Not real2.RetrieverForBaidu")
	}

}

func inspect(retriever iretriever.Retriever) {
	fmt.Printf("%T %v \n", retriever, retriever)
	switch v := retriever.(type) {
	case mock.RetrieverForMock:
		fmt.Println("Agent: ", v.Version, v.Agent)
	case real2.RetrieverForBaidu:
		fmt.Println("Title", v.Title, v.Name)
	}
}

func getRetriever(name string) iretriever.Retriever {
	var retriever iretriever.Retriever
	if name == "baidu" {
		retriever = real2.RetrieverForBaidu{
			Name:  "Baidu",
			Title: "这是一个测试百度的测试",
		}
	} else if name == "mock" {
		retriever = &mock.RetrieverForMock{Agent: "Mozilla/5.0", Version: "1.0.1"}
	} else {
		panic("没有找到对应的类型")
	}
	return retriever
}
